package com.education.basic.service.impl;

import java.lang.reflect.Method;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yunshangwoniu.core.AbstractEntity;
import com.yunshangwoniu.core.Assert.UserCommonAssert;
import com.yunshangwoniu.core.baseDao.BaseDao;
import com.yunshangwoniu.core.baseService.BaseService;
import com.yunshangwoniu.core.exception.UserCommonException;
import com.yunshangwoniu.core.page.Page;
import com.yunshangwoniu.core.utils.DateUtils;

@Service("baseService")
public class BaseServiceImpl<T> implements BaseService<T>
{
	@Resource
	private BaseDao<T> baseDao;
	
	@Override
	public T getObjectById(Class<?> t, Object id)
	{
		return baseDao.getById(t, id);
	}

	@Override
	public T saveObject(T t)
	{
		AbstractEntity ab = (AbstractEntity)t;
		ab.setCreateTime(System.currentTimeMillis());
		ab.setCreateTimeStr(DateUtils.getCurrentTime());
		ab.setLastAccessStr(DateUtils.getCurrentTime());
		ab.setLastAccess(System.currentTimeMillis());
		return baseDao.save(t);
	}

	@Override
	public void deleteObjectById(Class<?> t, Object id)
	{
		baseDao.deleteById(t, id);
	}

	@Override
	public T getObjectByUsername(Class<?> t, Object username)
	{
		return baseDao.getByUsername(t, username);
	}

	@Override
	public T getObjectByName(Class<?> t, Object name)
	{
		return baseDao.getByName(t, name);
	}

	@Override
	public Page<T> queryObject(Page<T> page, Class<?> c)
	{
		return baseDao.query( page, c);
	}

	@Override
	public void updateObject(T t)
	{
		AbstractEntity ab = (AbstractEntity)t;
		long id  = ab.getId();
		T t2 = getObjectById(t.getClass(), id);
		UserCommonAssert.notNull(t2, "您要更新的数据已经不存在！");
		Class<? extends Object> c = t.getClass();
		Class<? extends Object> c2 = t2.getClass();
		Method[] methods = c.getDeclaredMethods();
		for(Method m:methods)
		{
			String methodName = m.getName();
			if(methodName.contains("set"))
			{
				try
				{
					String t2MName = methodName.replaceFirst("set", "get");
					Method t2M = c2.getMethod(t2MName,  new Class<?>[0]);
					Object args = t2M.invoke(t, new Object[0]);
					m.invoke(t2, args);
				}catch(Exception e)
				{
					throw new UserCommonException("系统异常"); 
				}
			}
		}
		baseDao.update(t2);
	}

	@Override
	public void batchDeleteObject(List<Long> ids, Class<?> c)
	{
		UserCommonAssert.notEmpty(ids, "没有找到批量删除的id");
		baseDao.batchDelete(ids, c);
	}
}
